package u.hnx.admin.exception;

import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.yaml.snakeyaml.constructor.DuplicateKeyException;
import u.hnx.admin.security.api.HttpStatusAPI;

import java.nio.file.AccessDeniedException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestControllerAdvice
public class CommonExceptionHandler implements HttpStatusAPI {
    private Map<String,Object> map = new HashMap<>();
    @ExceptionHandler(BindException.class)
    public Map<String,Object> handleException(BindException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        String defaultMessage = allErrors.get(0).getDefaultMessage();
        return toJson(ex,defaultMessage);
    }
    @ExceptionHandler(DuplicateKeyException.class)
    public Map<String,Object> handleException(DuplicateKeyException ex) {
        return toJson(ex,DEFAULT_HTTP_REPEAT_ERROR_MSG);
    }

    @ExceptionHandler(AccessDeniedException.class)
    public Map<String,Object> accessDeniedException(AccessDeniedException e) {
        return toJson(e);
    }
    @ExceptionHandler(Exception.class)
    public Map<String,Object> handleException(Exception ex) {
        return toJson(ex);
    }
    private <T extends Exception> Map<String,Object> toJson(T ex,String... msg){
        map.put(CODE_TAG,DEFAULT_HTTP_ERROR_CODE);
        String message = msg.length > 0 ? msg[0]:ex.getMessage();
        map.put(MSG_TAG, message);
        return map;
    }
}
